<template>
  <div class="join-url-container">
    <div v-if="isWxWork" class="wecom-warning">
      <div class="background-animation"></div>
      <div class="wecom-logo-container">
        <img src="@/assets/images/newlog.png" alt="富创云会议" class="logo" />
        <span class="logo-text">富创云会议</span>
      </div>
      <div class="join-content wecom-tip-content">
        <h1>企业微信提示</h1>
        <div class="wecom-message">
          <p>您正在使用<span class="highlight">企业微信内置浏览器</span>浏览本页面</p>
          <p>请点击右上角</p>
          <p>选择<span class="highlight">"在浏览器中打开"</span></p>
        </div>
      </div>
    </div>
    <div v-else class="main-content-flex">
      <div class="background-animation"></div>
      <div class="logo-container">
        <img src="@/assets/images/newlog.png" alt="富创云会议" class="logo" />
        <span class="logo-text">富创云会议</span>
      </div>
      <div class="join-content-wrapper">
        <div class="join-content">
          <h1>加入会议</h1>
          <div class="meeting-info">
            <div class="info-item">
              <span class="label">会议号：</span>
              <span class="value">{{ conferenceId || '加载中...' }}</span>
              <a-button
                size="small"
                style="margin-left: 12px"
                :disabled="!conferenceId"
                @click="handleCopyConferenceId"
              >
                复制会议号
              </a-button>
            </div>
            <div class="info-item">
              <span class="label">会议主题：</span>
              <span class="value">{{ meetingInfo.subject || '加载中...' }}</span>
            </div>
            <div class="info-item">
              <span class="label">会议时间：</span>
              <span class="value">{{ formatTime(meetingInfo.startTime) || '加载中...' }} - {{ formatTime(meetingInfo.endTime, false) || '加载中...' }}</span>
            </div>
            <div class="info-item">
              <span class="label">会议类型：</span>
              <span class="value">{{ getMeetingType(meetingInfo.meetType) || '加载中...' }}</span>
            </div>
            <div class="info-item">
              <span class="label">会议地点：</span>
              <span class="value">{{ meetingInfo.meetType === 1 ? '线上会议' : (meetingInfo.location || '线下会议') }}</span>
            </div>
            <div class="info-item">
              <span class="label">来宾密码：</span>
              <span class="value">
                <template v-if="!meetingInfo.guestPassword || meetingInfo.guestPassword === ''">
                  无需密码
                </template>
                <template v-else>
                  {{ meetingInfo.guestPassword }}
                </template>
              </span>
              <a-button
                size="small"
                style="margin-left: 12px"
                :disabled="!meetingInfo.guestPassword || meetingInfo.guestPassword === ''"
                @click="handleCopyPassword"
              >
                复制密码
              </a-button>
            </div>
          </div>
        </div>
      </div>
      <div class="action-buttons-fixed">
        <div v-if="meetingInfo.endTime && isMeetingEnded" class="meeting-ended-tip">
          会议已经结束
        </div>
        <div class="download-tip">
          没有富创云会议？<a href="https://meeting.fortunesemic.com/download" target="_blank" rel="noopener" class="download-link">请点击这里下载</a>
        </div>
        <a-button type="primary" size="large" :disabled="isMeetingEnded" @click="handleStartApp">
          <template #icon><IconDesktop /></template>
          启动富创云会议加入
        </a-button>
        <a-button type="outline" size="large" :disabled="isMeetingEnded" @click="handleJoinBrowser">
          <template #icon><IconLink /></template>
          通过浏览器或华为云会议加入
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconDesktop, IconLink } from '@arco-design/web-vue/es/icon'
import { useRoute } from 'vue-router'
import request from '@/utils/request'

// 设置页面标签页title
if (typeof window !== 'undefined') {
  document.title = '富创云会议'
}

interface MeetingInfo {
  conferenceId: string
  subject: string
  location: string | null
  startTime: string | null
  endTime: string | null
  meetType: number
  circleType: number
  mediaType: number
  huaweiUrl: string
  guestPassword: string
}

const route = useRoute()
const conferenceId = ref('')

const meetingInfo = ref<MeetingInfo>({
  conferenceId: '',
  subject: '',
  location: null,
  startTime: null,
  endTime: null,
  meetType: 1,
  circleType: 0,
  mediaType: 1,
  huaweiUrl: '',
  guestPassword: ''
})

// 检测是否在企业微信内置浏览器中 - 增强版检测
const isWxWork = ref(false)

const checkBrowser = () => {
  const ua = navigator.userAgent.toLowerCase()
  isWxWork.value = ua.includes('wxwork') || ua.includes('wxworklocal')
}

// 获取会议信息
const getMeetingInfo = async () => {
  // 如果是企业微信浏览器，不加载会议信息
  if (isWxWork.value) return

  try {
    // 从URL获取conferenceId
    const id = route.query.conferenceId as string
    if (!id) {
      Message.error('缺少会议ID')
      return
    }
    conferenceId.value = id

    // 调用后端API获取会议信息
    const response = await request.get('/system/meet/joinMeet', {
      params: {
        conferenceId: id
      }
    })

    // 直接使用 response.data，因为响应拦截器已经处理了 code 判断
    meetingInfo.value = response.data
  } catch (error) {
    console.error('获取会议信息失败:', error)
    Message.error('获取会议信息失败')
  }
}

// 格式化时间
const formatTime = (time: string | null, showDate = true) => {
  if (!time) return ''
  // 处理 YYYY-MM-DD HH:mm:ss 格式
  const [datePart, timePart] = time.split(' ')
  if (!datePart || !timePart) return time

  // 只取时分，去掉秒数
  const [hours, minutes] = timePart.split(':').slice(0, 2)

  // 判断是否为移动端
  const isMobile = window.innerWidth <= 600

  if (!showDate) {
    return `${hours}:${minutes}`
  }
  if (isMobile) {
    // 只显示月日
    const [, month, day] = datePart.split('-')
    return `${month}-${day} ${hours}:${minutes}`
  }
  return `${datePart} ${hours}:${minutes}`
}

// 获取会议类型
const getMeetingType = (type: number) => {
  return type === 1 ? '线上会议' : '线下会议'
}

// 启动软件加入
const handleStartApp = () => {
  if (!conferenceId.value) {
    Message.error('缺少会议ID')
    return
  }
  // 使用 fuchuang:// 协议唤醒本地软件
  const appUrl = `fuchuang://join/${conferenceId.value}`
  window.location.href = appUrl
  Message.info('正在启动会议软件...')
}

// 通过浏览器加入
const handleJoinBrowser = () => {
  if (!conferenceId.value) {
    Message.error('缺少会议ID')
    return
  }
  if (meetingInfo.value.huaweiUrl) {
    window.location.href = meetingInfo.value.huaweiUrl
  } else {
    Message.error('获取加入链接失败')
  }
}

// 复制文本，兼容所有浏览器
const copyText = async (text: string, fallbackMsg = '复制失败，请手动复制', successMsg = '已复制') => {
  // 优先使用 clipboard API
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text)
      Message.success(successMsg)
      return true
    } catch {
      // 继续降级
    }
  }
  // 降级方案：使用 input + execCommand
  try {
    const input = document.createElement('input')
    input.value = text
    input.setAttribute('readonly', 'readonly')
    input.style.position = 'absolute'
    input.style.left = '-9999px'
    document.body.appendChild(input)
    input.select()
    const result = document.execCommand('copy')
    document.body.removeChild(input)
    if (result) {
      Message.success(successMsg)
      return true
    }
  } catch {
    // 继续降级
  }
  // 最后：移动端提示手动复制
  if (/mobile|android|iphone|ipad|micromessenger|wxwork/i.test(navigator.userAgent)) {
    Message.info('请长按会议号手动复制')
  } else {
    Message.error(fallbackMsg)
  }
  return false
}

// 复制嘉宾密码
const handleCopyPassword = async () => {
  if (!meetingInfo.value.guestPassword) return
  await copyText(meetingInfo.value.guestPassword, '复制失败，请手动复制', '嘉宾密码已复制')
}

// 复制会议号
const handleCopyConferenceId = async () => {
  if (!conferenceId.value) return
  await copyText(conferenceId.value, '复制失败，请手动复制', '会议号已复制')
}

// 判断会议是否已结束
const isMeetingEnded = computed(() => {
  if (!meetingInfo.value.endTime) return false
  // 会议结束时间格式：YYYY-MM-DD HH:mm:ss
  const end = new Date(meetingInfo.value.endTime.replace(/-/g, '/'))
  return Date.now() > end.getTime()
})

onMounted(() => {
  checkBrowser()
  getMeetingInfo()
})
</script>

<style scoped>
.join-url-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  height: 100vh;
  background: #f6f8fa;
  position: relative;
  overflow: hidden;
}
.main-content-flex {
  display: flex;
  flex-direction: column;
  flex: 1 1 auto;
  min-height: 0;
  height: 100%;
  position: relative;
}
.join-content-wrapper {
  flex: 1 1 auto;
  min-height: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  align-items: center;    /* 水平居中 */
}
.action-buttons-fixed {
  flex-shrink: 0;
  background: #fff;
  padding: 10px 16px 16px 16px;
  box-shadow: 0 -2px 8px rgba(30,58,138,0.04);
  display: flex;
  flex-direction: column;
  gap: 0.7rem;
  align-items: stretch;
  z-index: 10;
}
.download-tip {
  text-align: center;
  font-size: 13px;
  color: #888;
  margin-bottom: 4px;
}
.download-link {
  color: #1e3a8a;
  text-decoration: underline;
  margin-left: 2px;
}
@media (max-width: 600px) {
  .join-url-container {
    min-height: 100vh !important;
    height: 100vh !important;
    padding: 0 !important;
    overflow: hidden !important;
  }
  .main-content-flex {
    height: 100%;
    min-height: 0;
  }
  .join-content-wrapper {
    flex: 1 1 auto;
    min-height: 0;
    overflow-y: auto;
    padding-bottom: 0 !important;
  }
  .action-buttons-fixed {
    position: sticky;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 20;
    background: #fff;
    padding: 8px 8px 88px 8px !important;
    box-shadow: 0 -2px 8px rgba(30,58,138,0.06);
    gap: 0.6rem !important;
  }
  .download-tip {
    font-size: 12px !important;
    margin-bottom: 2px !important;
  }
  .meeting-ended-tip {
    font-size: 14px !important;
    margin-bottom: 4px !important;
  }
}
.wecom-warning {
  position: relative;
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wecom-tip-content {
  max-width: 400px;
  margin: 40px auto;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 8px;
  padding: 24px 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.wecom-tip-content h1 {
  font-size: 20px;
  color: #faad14;
  margin-bottom: 18px;
  text-align: center;
}
.wecom-message {
  display: flex;
  flex-direction: column;
  gap: 12px;
  font-size: 16px;
  color: #333;
  text-align: center;
}
.wecom-message .highlight {
  color: #faad14;
  font-weight: bold;
}
@media (max-width: 600px) {
  .wecom-tip-content {
    max-width: 95vw;
    padding: 18px 6px;
    margin: 24px 2vw;
    padding-top: 60px !important;
  }
  .wecom-tip-content h1 {
    font-size: 18px;
    margin-bottom: 12px;
  }
  .wecom-message {
    font-size: 15px;
    gap: 8px;
  }
}
.wecom-tip-content h1 {
  color: #1e3a8a;
  margin-bottom: 2rem;
}

.wecom-message {
  text-align: center;
}

.wecom-message p {
  margin: 0.8rem 0;
  font-size: 16px;
  color: #333;
  line-height: 1.6;
}

.highlight {
  color: #1e3a8a;
  font-weight: bold;
  padding: 0 4px;
}

.warning-content {
  max-width: 600px;
  margin: 0 auto;
}

.background-animation {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(-45deg, #1e3a8a, #3b82f6, #60a5fa, #93c5fd);
  background-size: 400% 400%;
  animation: gradient 15s ease infinite;
  z-index: 0;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.logo-container {
  position: fixed;
  top: 20px;
  left: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 2;
}

.logo {
  width: 32px;
  height: 32px;
}

.logo-text {
  color: #ffffff;
  font-size: 20px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.join-content {
  background: rgba(255, 255, 255, 0.95);
  padding: 3rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 800px;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(10px);
}

h1 {
  text-align: center;
  margin-bottom: 3rem;
  color: #1e3a8a;
  font-size: 32px;
  font-weight: 600;
}

.meeting-info {
  margin-bottom: 3rem;
  padding: 2rem;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(59, 130, 246, 0.1);
}

.info-item {
  margin: 1rem 0;
  display: flex;
  align-items: center;
}

.label {
  color: #1e3a8a;
  width: 100px;
  flex-shrink: 0;
  font-weight: 500;
  font-size: 16px;
}

.value {
  color: #1e40af;
  flex: 1;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  margin-top: 3rem;
}

.action-buttons :deep(.arco-btn) {
  height: 48px;
  font-size: 18px;
  transition: all 0.3s ease;
}

.action-buttons :deep(.arco-btn-primary) {
  background: #1e3a8a;
  border-color: #1e3a8a;
}

.action-buttons :deep(.arco-btn-primary:hover) {
  background: #1e40af;
  border-color: #1e40af;
}

.action-buttons :deep(.arco-btn-outline) {
  color: #1e3a8a;
  border-color: #1e3a8a;
}

.action-buttons :deep(.arco-btn-outline:hover) {
  color: #1e40af;
  border-color: #1e40af;
  background: rgba(30, 58, 138, 0.1);
}

.action-buttons :deep(.arco-btn-icon) {
  margin-right: 8px;
}

.download-tip {
  text-align: center;
  font-size: 13px;
  color: #888;
  margin-bottom: 4px;
}

.download-link {
  color: #1e3a8a;
  text-decoration: underline;
  margin-left: 2px;
}

@media (max-width: 600px) {
  .join-url-container {
    flex-direction: column !important;
    justify-content: flex-start !important;
    align-items: stretch !important;
    padding: 0 !important;
    min-height: 100vh !important;
    background: #f6f8fa !important;
    overflow: hidden !important;
    display: flex !important;
    position: static !important;
  }
  .logo-container {
    position: static !important;
    flex-direction: row !important;
    justify-content: flex-start !important;
    align-items: center !important;
    margin-bottom: 6px !important;
    width: 100% !important;
    gap: 4px !important;
    padding-left: 8px !important;
    height: 38px !important;
  }
  .logo {
    width: 22px !important;
    height: 22px !important;
  }
  .logo-text {
    font-size: 15px !important;
    color: #1e3a8a !important;
    text-shadow: none !important;
    font-weight: 700 !important;
  }
  .join-content, .wecom-tip-content {
    padding: 0.7rem 0.3rem 0.7rem 0.3rem !important;
    max-width: 98vw !important;
    min-width: 0 !important;
    border-radius: 10px !important;
    box-shadow: 0 1px 4px rgba(0,0,0,0.04) !important;
    margin: 0 auto 6px auto !important;
    margin-top: 2vw !important;
  }
  .meeting-info {
    padding: 0.5rem 0.2rem 0.5rem 0.2rem !important;
    margin-bottom: 0.7rem !important;
    font-size: 16px !important;
    border-radius: 8px !important;
    background: #fafdff !important;
    border: 1px solid #e3e8ee !important;
    box-shadow: 0 1px 2px rgba(30,58,138,0.02) !important;
  }
  .info-item {
    flex-direction: column !important;
    align-items: flex-start !important;
    margin: 0.5rem 0 0.5rem 0 !important;
    padding-bottom: 0.4rem !important;
    border-bottom: 1px solid #f0f2f5 !important;
    width: 100% !important;
  }
  .info-item:last-child {
    border-bottom: none !important;
  }
  .label {
    font-size: 15px !important;
    width: auto !important;
    margin-bottom: 1px !important;
    color: #1e3a8a !important;
    font-weight: 600 !important;
  }
  .value {
    font-size: 15px !important;
    word-break: break-all !important;
    color: #1e40af !important;
    margin-bottom: 2px !important;
  }
  .action-buttons {
    gap: 0.7rem !important;
    margin-top: 0.7rem !important;
    margin-bottom: 0.7rem !important;
    width: 100% !important;
    display: flex !important;
    flex-direction: column !important;
    align-items: stretch !important;
  }
  :deep(.arco-btn) {
    height: 40px !important;
    font-size: 16px !important;
    border-radius: 7px !important;
    width: 100% !important;
    margin: 0 auto !important;
    box-sizing: border-box !important;
  }
  :deep(.arco-btn + .arco-btn) {
    margin-top: 0.4rem !important;
  }
  h1 {
    font-size: 19px !important;
    margin-bottom: 0.7rem !important;
    text-align: center !important;
    color: #1e3a8a !important;
    font-weight: 700 !important;
  }
  .wecom-tip-content h1 {
    font-size: 17px !important;
    margin-bottom: 0.6rem !important;
  }
  .background-animation {
    border-radius: 0 0 18px 18px !important;
    z-index: 0 !important;
  }
  .download-tip {
    font-size: 12px !important;
    margin-bottom: 2px !important;
  }
}
.meeting-ended-tip {
  color: #e53e3e;
  text-align: center;
  font-size: 15px;
  margin-bottom: 6px;
  font-weight: 600;
}
</style>

<style scoped>
.wecom-logo-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 48px;
  background: #fff;
  z-index: 20;
  display: flex;
  align-items: center;
  padding-left: 16px;
  box-shadow: 0 2px 8px rgba(30,58,138,0.04);
}
.wecom-logo-container .logo {
  width: 32px;
  height: 32px;
}
.wecom-logo-container .logo-text {
  font-size: 18px;
  color: #1e3a8a;
  font-weight: 700;
  margin-left: 8px;
}
@media (max-width: 600px) {
  .wecom-logo-container {
    height: 38px;
    padding-left: 8px;
  }
  .wecom-logo-container .logo {
    width: 22px;
    height: 22px;
  }
  .wecom-logo-container .logo-text {
    font-size: 15px;
    margin-left: 4px;
  }
  .wecom-tip-content {
    padding-top: 60px !important;
  }
}
</style>
